<?php

namespace app\service;

use app\modules\front\model\UserLoginModel;
use yii\console\Exception;
use yii\filters\auth\AuthMethod;
use yii\web\UnauthorizedHttpException;

/**
 * 前台检测用户登录权限类
 * ©wpj
 */
class AuthFrontService extends AuthMethod
{

    /**
     * Token参数
     * @var string
     */
    public $tokenParam = 'token';

    /**
     * 构造函数
     * AuthBackendService constructor.
     * @param array $config
     * @throws UnauthorizedHttpException
     */
    public function __construct(array $config = [])
    {
        parent::__construct($config);
    }

    /**
     * 验证登录
     * @param \yii\web\User $user
     * @param \yii\web\Request $request
     * @param \yii\web\Response $response
     * @return bool|\yii\web\IdentityInterface
     * @throws Exception
     */
    public function authenticate($user, $request, $response)
    {

        ### token
        $token = $request->getHeaders()->get($this->tokenParam);
        if (!is_string($token) || empty($token)) {
            throw new Exception('请登录您的账号', 401);
        }

        ### 用户登录信息
        $identity = (new UserLoginModel())->findIdentityByAccessToken($token, get_class($this));
        if (!$identity) {
            throw new Exception('您的账号登录已过期，请重新登录', 401);
        }

        ### 设置登录信息
        \Yii::$app->getUser()->setIdentity($identity);

        return true;
    }
}
